package com.sumainfor.pc.market.service;

import com.google.common.collect.Lists;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.pc.market.dao.GmfWorkBenchMapper;
import com.sumainfor.pc.market.dao.MarketDataMapper;
import com.sumainfor.pc.market.feign.BaseFeignGmio;
import com.sumainfor.pc.market.feign.BaseFeignZuul;
import com.sumainfor.pc.market.util.FilterCenterUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Eddy·Chen
 * @Email 835033913@qq.com
 * @Create 2019-05-20 10:58
 * 总经办工作台
 */
@Service
@Log4j2
public class GmfWorkBenchService {

    @Autowired
    private GmfWorkBenchMapper mapper;

    @Autowired
    private MarketDataMapper marketDataMapper;

    @Autowired
    private BaseFeignZuul zuul;

    @Autowired
    private BaseFeignGmio gmio;

    /**
     * 获取全部的服务中心列表数据
     *
     * @return
     */
    public JsonResult getAllCenter() {
        List<Map<String, Object>> list = zuul.getCenterServiceIdList(null);
        return JsonResult.success(CustomMap.removeRepeatMapByKey(list, "id"));
    }


    /**
     * mvn
     * 获取服务中心的统计
     *
     * @param miID
     * @return
     */
    public JsonResult getCenterStatistics(Integer miID) {
        List<Integer> miIds = Lists.newArrayList();
        if (miID == null) {
            List<Map<String, Object>> list = zuul.getCenterServiceIdList(null);
            miIds.addAll(list.stream().map(item -> MapUtils.getInteger(item, "id")).collect(Collectors.toList()));
        } else {
            miIds.add(miID);
        }
        CustomMap dataMap = CustomMap.create();
        //获取统计查询
        //查询再跟客户
        List<Integer> userIds = marketDataMapper.selectAllWorderUserIds(null, null);
        List<Integer> uids = FilterCenterUtil.yamengFilterCenterUserId(userIds, miIds);
        if (uids.size() == 0) {
            dataMap.put("TenantCount", 0);
        } else {
            dataMap.put("TenantCount", marketDataMapper.selectWorderCount(uids, null, null));
        }
        //计算空置率
        int sum = mapper.selectCenterForEmpty(miIds, null);
        int emSum = mapper.selectCenterForEmpty(miIds, "1");
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        dataMap.put("EmptyRate", numberFormat.format((float) emSum / (float) sum * 100));

        //全部再跟业主
        dataMap.put("OwnerCount", mapper.selectCenterForOwner(miIds));

        //新收待装修房源
        dataMap.put("WaitCount", mapper.selectCenterForWaitPlanCount(miIds, 3));

        //装修中房源
        dataMap.put("PlanIngCount", mapper.selectCenterForWaitPlanCount(miIds, 4));

        return JsonResult.success(dataMap);
    }

    /**
     * 查询全部分公司统计信息
     *
     * @param areaId
     * @return
     */
    public JsonResult getCompanyStatistics(Integer areaId, String startTime, String endTime) {
        List<Integer> miIds = Lists.newArrayList();
        if (areaId == null) {
            List<Map<String, Object>> list = zuul.getCenterServiceIdList(null);
            miIds.addAll(list.stream().map(item -> MapUtils.getInteger(item, "id")).collect(Collectors.toList()));
        } else {
            List<Map<String, Object>> list = zuul.getCenterServiceIdList(areaId);
            miIds.addAll(list.stream().map(item -> MapUtils.getInteger(item, "id")).collect(Collectors.toList()));
        }

        CustomMap dataMap = CustomMap.create();

        //新签出租
        dataMap.put("NewPactCount", mapper.selectComForNewPact(miIds, startTime, endTime, null));

        //新增咨询租客
        dataMap.put("NewTenantCount", mapper.selectComForTenant(miIds, startTime, endTime));

        //新增带看工单
        dataMap.put("NewWorkOrderCount", mapper.selectComForWord(miIds, startTime, endTime));

        //低于活动价签约
        dataMap.put("MinActivateCount", mapper.selectComForMoneyMinPact(miIds, startTime, endTime));

        //新增续租
        dataMap.put("NewPlusPact", mapper.selectComForNewPact(miIds, startTime, endTime, 1));

        //定价异常审核
        dataMap.put("MoneyAuditCount", mapper.selectComForMoneyAudit(miIds, startTime, endTime));

        //新签收房
        dataMap.put("NewOwnerHousingCount", mapper.selectComForNewHousing(miIds, startTime, endTime));

        //开工房源
        dataMap.put("PlanIngHousingCount", mapper.selectComForPlanIngHousing(miIds, startTime, endTime, 4));

        //通过验收房源
        dataMap.put("CheckSuccessHousingCount", mapper.selectComForPlanIngHousing(miIds, startTime, endTime, 7));

        //全部空置房源
        dataMap.put("EmptyAllCount", mapper.selectComForEmpty(miIds, startTime, endTime, false));

        //空置超30天房源
        dataMap.put("EmptyAllFor30Count", mapper.selectComForEmpty(miIds, startTime, endTime, true));

        //服务调用
        dataMap.putAll(gmio.getComFieldData(CustomMap.create("miIds", miIds)
                .put("startTime", startTime)
                .put("endTime", endTime)));
        return JsonResult.success(dataMap);
    }


    /**
     * 查询年度收房统计
     *
     * @param year
     * @return
     */
    public JsonResult getYearInHousing(String year) {
        if (StringUtils.isBlank(year)) {
            year = DateTime.now().toString("yyyy");
        }
        List<String> label = Lists.newArrayList();
        CustomMap data = CustomMap.create();
        List<CustomMap> values = Lists.newArrayList();
        int sumCount = 0;
        data.put("values", values);
        data.put("labels", label);

        List<Map<String, Object>> list = mapper.selectInHousing(year);

        for (int i = 1; i <= 12; i++) {
            label.add(i + "月");
            CustomMap map = CustomMap.create();
            values.add(map);
            map.put("name", i + "月");
            map.put("value", 0);
            for (Map<String, Object> item : list) {
                if (MapUtils.getInteger(item, "month").equals(i)) {
                    int sum = MapUtils.getIntValue(item, "sum");
                    map.put("value", sum);
                    sumCount += sum;
                    break;
                }
            }
        }
        data.put("sumCount", sumCount);
        return JsonResult.success(data);
    }

    /**
     * 查询年度租房统计
     *
     * @param year
     * @return
     */
    public JsonResult getYearOutHousing(String year) {
        if (StringUtils.isBlank(year)) {
            year = DateTime.now().toString("yyyy");
        }
        List<String> label = Lists.newArrayList();
        CustomMap data = CustomMap.create();
        List<CustomMap> values = Lists.newArrayList();
        int sumCount = 0;
        data.put("values", values);
        data.put("labels", label);

        List<Map<String, Object>> list = mapper.selectOutHousing(year);

        for (int i = 1; i <= 12; i++) {
            label.add(i + "月");
            CustomMap map = CustomMap.create();
            values.add(map);
            map.put("name", i + "月");
            map.put("value", 0);
            for (Map<String, Object> item : list) {
                if (MapUtils.getInteger(item, "month").equals(i)) {
                    int sum = MapUtils.getIntValue(item, "sum");
                    map.put("value", sum);
                    sumCount += sum;
                    break;
                }
            }
        }
        data.put("sumCount", sumCount);
        return JsonResult.success(data);
    }

    /**
     * 投诉类型统计
     *
     * @param year
     * @return
     */
    public JsonResult getComplaint(String year) {
        if (StringUtils.isBlank(year)) {
            year = DateTime.now().toString("yyyy");
        }
        //投诉内容  1.邻里纠纷  2.管家服务  3.维修服务 4.财务打款  5.房屋质量  6.其他
        CustomMap originalVal = CustomMap.create("1", "邻里纠纷")
                .put("2", "管家服务")
                .put("3", "维修服务")
                .put("4", "财务打款")
                .put("5", "房屋质量")
                .put("6", "其他");
        CustomMap data = CustomMap.create();
        data.put("labels", originalVal.values());
        List<Map<String, Object>> values = Lists.newArrayList();
        data.put("values", values);
        List<Map<String, Object>> dataList = gmio.getComplaint(year);
        int sumCount = 0;
        for (Map.Entry<String, Object> entry : originalVal.entrySet()) {
            CustomMap item = CustomMap.create("name", entry.getValue());
            item.put("value", 0);
            for (Map<String, Object> map : dataList) {
                int count = MapUtils.getIntValue(map, "value");
                if (entry.getValue().equals(MapUtils.getString(map, "name"))) {
                    item.put("value", count);
                    sumCount += count;
                    break;
                }
            }
            values.add(item);
        }
        data.put("sumCount", sumCount);
        return JsonResult.success(data);
    }

}
